import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import Calendar from "./calendar";

import {
    Popconfirm,
    Input,
    Button,
    Row,
    Col,
    Menu,
    Dropdown,
    // Select,
    // DatePicker,
    // Tabs,
    Tag,
    Table,
    Modal, message
} from 'antd';
import { LoadingOutlined, PlusOutlined, CloseCircleOutlined, EyeInvisibleOutlined, EyeOutlined,DownOutlined } from '@ant-design/icons';
import axios from "@src/lib/axios";
import moment from 'moment';
import AddRoom from './AddRoom'
const { Column } = Table;


@withRouter
export default class Room extends Component {

    state = {
        visible: false,
        visible1: false,
        currRow: {},
        cost: '',
        costType: 1,
        params: {
            page: 1,
            size: 15,
            hotel_id: ''
        },
        loading:"",
        roomList: [],
        total: 0,
        hotel_id: '',
        room_id: '',
        dateRange: [moment(), moment('2020-12-1')],
        calendarVisible: false,
        filesList: [],
        calendarPrice: [],
        bedConf:{}
    }

    changeHandler = (k, v) => {
        this.setState({
            [k]: v
        })
    }

    getImgList = (hotel_id) => {
        axios.post('/product/hotel/image_manage', { hotel_id }).then(res => {
            if (res.code === 0) {
                this.setState({ filesList: res.data });
            }
        })
    };

    initCalendar = (room_id) => {
        axios.post('/product/hotel/room/room_date_price', { room_id }).then(res => {
            if (res.code === 0) {
                /*date_str: "2020-01-01"
                hotel_id: 1
                price: "666"
                price_id: 94
                room_id: 6*/
                if (res.data.length !== 0) {
                    let list = res.data.map((item) => ({
                        date: item.date_str,
                        team_price: item.team_price,
                        team_price_jiesuan:item.team_price_jiesuan,
                        sk_price:item.sk_price,
                        sk_price_jiesuan:item.sk_price_jiesuan,
                        zk_price:item.zk_price,
                        zk_price_jiesuan:item.zk_price_jiesuan
                    }))
                    this.setState({
                        dateRange: [ moment(list[0].date), moment(list[list.length - 1].date) ],
                        calendarPrice: list
                    });
                }
            }
        })
    }

    fetchData = () => {
        this.setState({ loading: true });
        const { params } = this.state;
        axios.post("/product/hotel/room/list", params).then(res => {
            if (res.code === 0) {
                let data = res.data;
                this.setState({
                    roomList: data.list,
                    total: data.total,
                });
                this.setState({ loading: false });
            }
        });
    };

    onOpera = (k, row) => {
        console.log(k,row)
        switch (k) {
            case 0:
                this.del(row);
                break;
            case 1:
                this.initCalendar(row.room_id);
                this.setState({
                    calendarVisible: true,
                    room_id: row.room_id
                });
                break;
            case 2:
                axios.post("/product/hotel/room/sale", {
                    status: row.status === 1? 2 : 1,
                    room_id: row.room_id
                }).then(res => {
                    if (res.code === 0) {
                        message.success("操作成功！");
                        this.fetchData();
                    }
                });
                break;
            case 3:
                this.state.costType = 1;
                this.state.currRow = row;
                this.setState({ currRow: row, cost: row.rebate_buyer, visible1: true });
                break;
            case 4:
                this.state.costType = 2;
                this.state.currRow = row;
                this.setState({ currRow: row, cost: row.rebate, visible1: true });
                break;
        }
    };

    del = ({hotel_id, room_id}) => {
        axios.post("/product/hotel/room/del", {
            hotel_id,
            room_id
        }).then(res => {
            if (res.code === 0) {
                message.success("删除成功！");
                this.fetchData();
            }
        });
    }

    toEdit = ({hotel_id, room_id}) => {
        this.setState({
            visible: true,
            hotel_id,
            room_id
        });
    }

    addRom = () => {
        this.setState({ room_id: '' })
        this.changeHandler('visible', true);
    }

    getCalendar = (data,value) => {
        console.log('price=====', data);
        if (data.length === 0) {
            return;
        }
        const { hotel_id, room_id } = this.state;

        let list = data.filter(item =>
            item.team_price !== '' &&
            item.team_price_jiesuan!=="" &&
            item.sk_price !== "" &&
            item.sk_price_jiesuan!==""&&
            item.zk_price !== "" &&
            item.zk_price_jiesuan !== ""
        );
        list = list.map(item => (
            {
                date: item.date,
                team_price: item.team_price,
                team_price_jiesuan:item.team_price_jiesuan,
                sk_price:item.sk_price,
                sk_price_jiesuan:item.sk_price_jiesuan,
                zk_price:item.zk_price,
                zk_price_jiesuan:item.zk_price_jiesuan
            }
            ));
        axios.post('/product/hotel/room/save_room_price', {
            hotel_id,
            room_id,
            list
        }).then(res => {
            message.success('保存成功！');
        });
    }

    onChangePage = (page) => {
        this.state.params.page = page;
        this.setState({
            params: { ...this.state.params }
        })
        this.fetchData();
    }

    handleOk = () => {
        axios.post(this.state.costType === 1? "/product/hotel/room/set_team_back_fee" : '/product/hotel/room/set_service_amount', {
            rebate: this.state.cost,
            room_id: this.state.currRow.room_id
        }).then(res => {
            this.setState({ visible1: false })
            if (res.code === 0) {
                message.success("操作成功！");
                this.fetchData();
            }
        });
    }

    onClickOperation = (key,row)=>{
        switch (key) {
            case 'edit':
                this.toEdit(row);
                break;
            case 'del':
                this.onOpera(0,row);
                break;
            case 'set_price':
                this.onOpera(1,row);
                break;
            case 'set_status':
                this.onOpera(2,row);
                break;
            case 'set_team_cash_back':
                this.onOpera(3,row);
                break;
            case 'set_platform_cash_back':
                this.onOpera(4,row);
                break;
        }
    }


    getOperation = (row) => {
        return (
        <Menu
            theme="dark"
            onClick={({key})=>this.onClickOperation(key,row)}
        >
            <Menu.Item key="edit">编辑</Menu.Item>
            <Menu.Item key="del">删除</Menu.Item>
            <Menu.Item key="set_price">设置价格</Menu.Item>
            <Menu.Item key="set_status"> {row.status===1?'下架':'上架'} </Menu.Item>
            <Menu.Item key="set_team_cash_back">团队分销返现</Menu.Item>
            <Menu.Item key="set_platform_cash_back">平台返现</Menu.Item>
        </Menu>
        )
    }

    getBedConf = () =>{
        axios.post('/platform/hotel/conf/bed/list').then(res=>{
            if (res.code === 0) {
                let {data} = res
                let bedConf = [];
                data.map(function (val) {
                    bedConf[val.id] = val.title
                    });
                this.setState({bedConf})
            }
        });
    }


    UNSAFE_componentWillMount() {
        this.getBedConf();
        let { hotel_id } = this.props.location.state || {};
        let dateRange = [moment(), moment('2020-12-1')]

        this.state.params.hotel_id = hotel_id;
        this.setState({
            params: { ...this.state.params },
            hotel_id,
            dateRange
        })
        this.fetchData();
        if (hotel_id) {
            this.getImgList(hotel_id);
        }
    }

    render() {
        let { visible, roomList, hotel_id, room_id,
            calendarVisible, filesList, dateRange,
            total, calendarPrice ,costType,bedConf} = this.state;

        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            getCheckboxProps: record => ({
                disabled: record.name === 'Disabled User', // Column configuration not to be checked
                name: record.name,
            }),
        };
        const modalTitle ={
            1:"设置团队价返佣",
            2:"设置平台服务费"
        };


        return (
            <div className="container">
                <Modal
                    title={modalTitle[costType]}
                    visible={this.state.visible1}
                    onOk={this.handleOk}
                    onCancel={() => this.setState({ visible1: false })}
                >
                    <Input addonAfter={`${process.env.CURRENCY}`} placeholder={this.state.costType === 1? '设置佣金' : '设置服务费'} type="text" value={this.state.cost} onChange={v => this.setState({cost: v.target.value})}/>
                </Modal>
                <Calendar
                    date={dateRange}
                    visible={calendarVisible}
                    priceList={calendarPrice}
                    emitChange={this.getCalendar}
                    setVisible={(v) => this.setState({ calendarVisible: v ,calendarPrice:[],dateRange:[moment(),moment('2020-12-1')]})}
                />
                <Row className="fields-box">
                    <Col span={24} style={{ marginBottom: '20px'}}>
                        <Button type="primary" style={{ marginRight: '20px'}} onClick={this.addRom}><PlusOutlined/>添加房型</Button>
                    </Col>
                </Row>
                <Table
                    rowKey="room_id"
                    size="small"
                    loading={this.state.loading}
                    dataSource={roomList}
                    pagination={{
                        total,
                        current: this.state.params.page,
                        pageSize: this.state.params.size,
                        onChange: this.onChangePage
                    }}
                >
                    <Column
                        align={"center"}
                        title="房型名称"
                        dataIndex="room_name"
                        key="room_name"
                    />
                    <Column
                        align={"center"}
                        title="床型"
                        dataIndex="conf_bed_id"
                        key="conf_bed_id"
                        render={(val) => {
                            return bedConf[val]
                        }}
                    />
                    <Column
                        align={"center"}
                        title="团队价返现"
                        dataIndex="team_fee"
                        key="team_fee"
                        render={(val) => <span>{val + `${process.env.CURRENCY}`}</span>}
                    />
                    <Column
                        align={"center"}
                        title="加床费"
                        dataIndex="extra_bed_price"
                        key="extra_bed_price"
                        render={(val) => <span>{val + `${process.env.CURRENCY}`}</span>}
                    />
                    <Column
                        align={"center"}
                        title="楼层"
                        dataIndex="floor"
                        key="floor"
                    />
                    <Column
                        align={"center"}
                        title="面积"
                        dataIndex="area"
                        key="area"
                        render={(val) => <span>{val + '㎡'}</span>}
                    />
                    <Column
                        align={"center"}
                        title="超值房型"
                        dataIndex="deserve"
                        key="deserve"
                        render={(val) => val === 1? <Button type="link">是</Button> : '否'}
                    />
                    <Column
                        align={"center"}
                        title="上/下架"
                        dataIndex="status"
                        key="status"
                        render={val =>
                            val == 1 ? (
                                    <Tag color="#87d068">上架</Tag>

                            ) : (
                                <Tag color="#f50">下架</Tag>

                            )}
                    />
                    <Column
                        align="center"
                        title="操作"
                        dataIndex="address"
                        key="address"
                        render={(val, row) => {
                                return (
                                    <Dropdown overlay={this.getOperation(row)}>
                                        <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                                            设置<DownOutlined />
                                        </a>
                                    </Dropdown>
                                )
                            }
                        }
                    />
                </Table>
                <AddRoom
                    visibleModal={visible}
                    hotel_id={hotel_id}
                    room_id={room_id}
                    getRoomList={this.fetchData}
                    filesList={filesList}
                    changeVisible={(v) => this.setState({ visible: v })}
                />
            </div>
        )
    }
}